package web.java.a_connectionPool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

/**
 * 自定义数据库连接池
 * 1、指定全局参数：初始化数目，最大连接数，当前连接数，连接池集合
 * 2、构造函数：循环三个链接
 * 3、写一个创建连接的方法
 * 4、获取连接：
 * 5、释放连接：连接放回集合中
 * */

public class Demo01_MyPool {
	
	public int init_count=3;
	public int max_count=6;
	public int current_count=0;
	private LinkedList<Connection> pool=new LinkedList<Connection>();
	
	public Demo01_MyPool() throws Exception{
		for(int i=0;i<init_count;i++){
			Connection conn=createConnection();
			pool.addLast(conn);
		}
	}
	
	private Connection createConnection() throws Exception{
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","root");
		return conn;
	}
	
	public Connection getConnection() throws Exception{
		if(pool.size()>0){
			current_count++;
			return pool.removeFirst();
		}
		
		if(current_count < max_count){
			current_count++;
			return createConnection();
		}
		
		throw new RuntimeException("当前连接已经达到最大连接数目！");
	}
	
	public void releaseConnection(Connection conn) throws SQLException{
		if(pool.size()<init_count){
			pool.addLast(conn);
		}else{
			current_count--;
			conn.close();
		}
	}
	
	public static void main(String[] args) throws Exception {
		Demo01_MyPool pool=new Demo01_MyPool();
		System.out.println(pool.init_count);
		System.out.println(pool.current_count);
		System.out.println(pool.pool.size());
		System.out.println();
		pool.getConnection();
		pool.getConnection();
		pool.getConnection();
		pool.getConnection();
		pool.getConnection();
		Connection conn1=pool.getConnection();
		conn1.close();
		System.out.println(pool.init_count);
		System.out.println(pool.current_count);
		System.out.println(pool.pool.size());
	}
}
